#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <math.h>
void zzzadventurercardplay(int drawntreasure, int currentPlayer, int cardDrawn,
                int temphand[MAX_HAND], int z, struct gameState* state);
				
int compare(const void* a, const void* b);

void checkAdventurer(int drawT, int p, int drawC, int tempH[MAX_HAND], int z, struct gameState *post)
{
	struct gameState pre;
	memcpy (&pre, post, sizeof(struct gameState));
	int r;
	printf ("It's failing at zzzadventurercardplay function\n");
	zzzadventurercardplay(drawT, p, drawC, tempH, z, post);
	
	while (drawT < 2)
	{
		if (pre.deckCount[p] < 1)
		{
			int newDeck[MAX_DECK];
			int newDeckPos = 0;
			int card;
			int i;
			
			qsort ((void*)(pre.deck[p]), pre.deckCount[p], sizeof(int), compare); 
			/* SORT CARDS IN DECK TO ENSURE DETERMINISM! */

			while (pre.deckCount[p] > 0) 
			{
				card = floor(Random() * pre.deckCount[p]);
				newDeck[newDeckPos] = pre.deck[p][card];
				newDeckPos++;
				for (i = card; i < pre.deckCount[p]-1; i++) 
				{
				  pre.deck[p][i] = pre.deck[p][i+1];
				}
				pre.deckCount[p]--;
			}
			for (i = 0; i < newDeckPos; i++) 
			{
				pre.deck[p][i] = newDeck[i];
				pre.deckCount[p]++;
			}
		}
			
		drawCard(p, &pre);
		drawC = pre.hand[p][pre.handCount[p]-1];
		if (drawC == copper || drawC == silver || drawC == gold)
			drawT++;
		else
		{
			tempH[z] = drawC;
			pre.handCount[p]--;
			z++;
		}
	}
	while (z - 1 >= 0)
	{
		pre.discard[p][pre.discardCount[p]++] = tempH[z-1];
		z = z - 1;
	}
	
	assert (post == 0);
	assert(memcmp(&pre, post, sizeof(struct gameState)) == 0);
}

int main() {

int i, n, r, p, deckCount, discardCount, handCount;
int temphand[MAX_HAND];
int z = 0;
int drawnTreasure = 0;
int cardDrawn;

 struct gameState G;
 int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
           sea_hag, tribute, smithy};
 
printf ("Testing adventurer card.\n");

printf ("RANDOM TESTS.\n"); 

SelectStream(2);
PutSeed(3);

for(n = 0; n < 2; n++)
{
	for (i=0; i < sizeof(struct gameState); i++)
	{
		((char*)&G)[i] = floor(Random() * 256);
	}
	p = floor(Random() * 2);
	G.deckCount[p] = floor(Random() * MAX_DECK);
	G.discardCount[p] = floor(Random() * MAX_DECK);
	G.handCount[p] = floor(Random() * MAX_HAND);
		printf ("1\n");
	checkAdventurer(drawnTreasure, p, cardDrawn, temphand, z, &G);
		printf ("99\n");
}

printf ("ALL TESTS OK\n");

exit(0);
}
